package cn.edu.sdjzu.xg.eagle.dao;

import cn.edu.sdjzu.xg.eagle.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao implements UserDaoInterface {
    private static UserDao userDao = new UserDao();
    private UserDao() {}
    public static UserDao getInstance() {
        return userDao;
    }

    @Override
    public boolean add(User user, Connection connection) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement
                ("insert into user" + "(username,password,teacher_id)" + "values (?,?,?)");
        preparedStatement.setString(1,user.getUsername());
        preparedStatement.setString(2,user.getPassword());
        preparedStatement.setLong(3,user.getTeacher().getId());

        int rowAffected = preparedStatement.executeUpdate();
        return rowAffected > 0;
    }

    @Override
    public boolean delete(String usename, Connection connection) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement("delete from user where username=?");
        preparedStatement.setString(1, usename);
        int rowAffected = preparedStatement.executeUpdate();
        return rowAffected >0;
    }
    @Override
    public void login(User user, Connection connection) throws SQLException {
        String sql = "select * from user where username=? and password=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, user.getUsername());
        preparedStatement.setString(2, user.getPassword());
        ResultSet resultSet = preparedStatement.executeQuery();
        if(resultSet.next()) {
            Long user_id = resultSet.getLong("id");
            user.setId(user_id);
        }
    }
}
